package com.ctec.controller;

import com.alibaba.fastjson2.JSON;
import com.ctec.mapper.ClickhouseMapper;
import com.ctec.util.R;
import com.ctec.util.RedisUtil;
import com.ctec.vo.DynamicData;
import com.ctec.vo.FiledItem;
import com.ctec.vo.TableFiledChangeForm;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@RequestMapping("meta")
@RestController
@Slf4j
public class TableFieldChangeController {


    @Autowired
    private RedisUtil redisUtil;


    @Resource
    private ClickhouseMapper clickhouseMapper;


    //{
    //   "tableName": "su_map",
    //   "filedItems": [
    //     {
    //       "fieldName": "ip",
    //       "fieldType": "String"
    //     },
    //     {
    //       "fieldName": "port",
    //       "fieldType": "UInt8"
    //     },
    //     {
    //       "fieldName": "company",
    //       "fieldType": "String"
    //     },   {
    //       "fieldName": "location",
    //       "fieldType": "String"
    //     }
    //     ,   {
    //       "fieldName": "desc",
    //       "fieldType": "String"
    //     }    ,   {
    //       "fieldName": "details",
    //       "fieldType": "String"
    //     }
    //   ]
    // }

    /**
     * 测试修改表结构
     * @param filedChangeForm
     * @return
     */
    @RequestMapping("tableFiledChange")
    public R tableFiledChange(@RequestBody TableFiledChangeForm filedChangeForm) {

        String table = filedChangeForm.getTableName(); // 变动的表名
        List<FiledItem> filedItems = filedChangeForm.getFiledItems();
        List<String> newFields = filedItems.stream().map(FiledItem::getFieldName).collect(Collectors.toList());


        // String type = "";  // 表结构怎么变化  ADD  DROP  su_map
        // List<String> newFields = Arrays.asList("ip", "os", "port", "newField");  // 需要调整的字段
        // List<String> newFields = new ArrayList<>(Arrays.asList("ip1", "port1", "newField", "newField2", "newField22"));  // 需要调整的字段

        List<String> originFields = clickhouseMapper.queryTableFieldsByTableName(table);

        // existFields.removeAll(currentFields);  //已经存在的字段 去除 当前提交的字段，剩下的字段就是多余的应该删除掉

        // 先求出原始列表和要排除列表的交集
        List<String> intersectionList = new ArrayList<>(originFields);
        intersectionList.retainAll(newFields);


        newFields.removeAll(intersectionList); //新增的字段去除交集的部分，就是要新增的字段

        for (String newField : newFields) {
            log.info("需要新增的字段 {}", newField);
            String fieldType = filedItems.stream().filter(filedItem -> filedItem.getFieldName().equals(newField)).findFirst().get().getFieldType();
            addColumn(table, newField,fieldType);
        }

        originFields.removeAll(intersectionList); //原来的字段去除掉交集的字段，就是多余的字段要删除

        for (String existField : originFields) {
            // 删除这些字段 ，务必小心删除
            log.info("需要删除的字段 {}", existField);
            deleteColumn(table, existField);

        }

        // ALTER TABLE su_map ADD COLUMN age UInt8;
        // ALTER TABLE su_map DROP COLUMN age;
        // String preSql = "ALTER TABLE " + table +  "   COLUMN "  " TEXT";
        // redisUtil.set("haha", "测试");

        return R.ok();

    }

    /**
     * 测试新增数据
     */
    @RequestMapping("insertSomeData")
    public R insertSomeData(@RequestBody DynamicData filedChangeForm) {

        String tableName = filedChangeForm.getTableName();
        for (HashMap filedItem : filedChangeForm.getFiledItems()) {
            clickhouseMapper.insertData(tableName, JSON.toJSONString(filedItem));
        }
        return R.ok();

    }

    /**
     * 查询数据
     */
    @RequestMapping("list")
    public R list(@RequestParam String tableName) {
        List list = clickhouseMapper.queryListByTableName(tableName);
        return R.ok(list);
    }


    /**
     * 增加字段
     *
     * @param table     操作的表名
     * @param field     操作的字段名
     * @param fieldType
     */
    private void addColumn(String table, String field, String fieldType) {
        clickhouseMapper.addColumn(table, field, fieldType);
    }

    /**
     * 删除字段
     * @param table 操作的表名
     * @param field 操作的字段名
     */
    private void deleteColumn(String table, String field) {
        clickhouseMapper.deleteColumn(table, field);
    }
}
